<?php
class Menu extends AppModel{
	public $name = 'Menu';
    public $hasOne = 'Page';

	public $validate = array(
		'title' => array(
			'rule'     => 'notEmpty',
			'required' => true,
			'message' => 'Title field is required.'
		)
	);
	
	public function isOwnedBy($artical, $user) {
		
		return $this->field('id', array('id' => $artical, 'user_id' => $user)) === $artical;
	}

	function find_parent_menu($menus){
		
		
		foreach($menus as $key=>$menu){
			$id=$menu['Menu']['id'];
			$parent_id=$menu['Menu']['parent_id'];
			$menu_title=$menu['Menu']['title'];
			
			if($parent_id !=0){
				$title = $this->find('first', array(
					'conditions' => array('Menu.id' => $parent_id)
				));
				
				$menus[$key]['Menu']['parent_menu']=$title['Menu']['title'];
			}else{
				$menus[$key]['Menu']['parent_menu']='';
			}
		}
		
		return $menus;
	}
	
	function parent_menu(){
		$menus = $this->query("select * from menus where menu_type='top'");
		return $menus;
	}
	

	function menu_tree($id=0){

		static $menus = array ();

		static $level = 0;

		$level ++;

		$result = $this->query("select * from menus where parent_id='".$id."' order by menu_order asc");

		
		foreach($result as $data){
			$rs[] = $data['menus'];
		}

		
		if(isset($rs)){
			foreach ($rs as $row) {

				$menus[$row['id']] = str_repeat('|__ ', $level -1) .'|__'. $row['title'];

				$this->menu_tree($row['id']);

			}
		}

		$level --;

		return $menus;

	}
	
	function menu_detailes($tree,$base_url){
		$menus = array();
		foreach($tree as $key=>$value){
			$page = $this->query("select * from pages where menu_id='".$key."'");
			$page_title = $page[0]['pages']['title'];
			$page_id = $page[0]['pages']['id'];
			
			$menu_res = $this->query("select * from menus where id='".$key."'");
			$menu_type = $menu_res[0]['menus']['menu_type'];
			
			if(!empty($page_title)){
				$info['id']=$key;
				$info['page_id']=$page_id;
				$info['page_title']="<a href='".$base_url."/Pages/edit/".$page_id."'>".$page_title."</a>";
				$info['menu']=$value;
				$info['menu_type']=$menu_type;
			}else{
				$info['id']=$key;
				$info['page_id']=$page_id;
				$info['page_title']="<a href='".$base_url."/Pages/add/".$key."'>Add</a>";
				$info['menu']=$value;
				$info['menu_type']=$menu_type;
			}
			
			$menus[] = $info;
			
		}
		
		return $menus;
	}

}

?>